package com.grace.cms.general.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import com.grace.cms.common.utils.ThemeUtils;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 全局请求异常处理器
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理所有未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    public ModelAndView handleGlobalException(Exception ex, HttpServletRequest request) {
        logger.error("发生未捕获的异常: ", ex);
        return createErrorResponse(request, HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage());
    }

    /**
     * 处理资源未找到异常（404）
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public ModelAndView handleNotFoundException(NoHandlerFoundException ex, HttpServletRequest request) {
        logger.warn("请求未找到: {}", ex.getMessage());
        return createErrorResponse(request, HttpStatus.NOT_FOUND, ex.getMessage());
    }

    /**
     * 处理资源未找到异常（404）
     */
    @ExceptionHandler(NoResourceFoundException.class)
    public ModelAndView handleNoResourceFoundException(NoResourceFoundException ex, HttpServletRequest request) {
        logger.warn("资源未找到: {}", ex.getMessage());
        return createErrorResponse(request, HttpStatus.NOT_FOUND, ex.getMessage());
    }

    /**
     * 处理非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ModelAndView handleIllegalArgumentException(IllegalArgumentException ex, HttpServletRequest request) {
        logger.warn("非法参数: {}",ex);
        return createErrorResponse(request, HttpStatus.BAD_REQUEST, ex.getMessage());
    }

    /**
     * 创建统一的错误响应格式
     */
    private ModelAndView createErrorResponse(HttpServletRequest request, HttpStatus status, String message) {
        ModelAndView errorResponse = new ModelAndView();
        String requestURI = request.getRequestURI();
        String contextPath = request.getContextPath();
        String relativePath = requestURI.substring(contextPath.length());
        String[] pathSegments = relativePath.split("/");
        // 判断是否有至少一个有效段（即 /themeName 的形式）
        String themeName = pathSegments[0];
        if (pathSegments.length > 1) {
            themeName = pathSegments[1]; // 获取第一个路径段作为 themeName
        }
        errorResponse.addObject("themeName", new String(themeName));
        errorResponse.setViewName(ThemeUtils.choosePath(status, themeName));
        errorResponse.addObject("status", status);
        errorResponse.addObject("message", message);
        errorResponse.setStatus(status);
        return errorResponse;
    }
}
